package com.sunlands.qdcy.deskmate.web;

import com.sunlands.qdcy.deskmate.common.annotation.AutoLog;
import com.sunlands.qdcy.deskmate.dao.pojo.OrderRecordDO;
import com.sunlands.qdcy.deskmate.enums.OrderStatus;
import com.sunlands.qdcy.deskmate.enums.YN;
import com.sunlands.qdcy.deskmate.exception.CheckParamException;
import com.sunlands.qdcy.deskmate.service.OrderRecordService;
import com.sunlands.qdcy.deskmate.vo.BusinessResult;
import com.sunlands.qdcy.deskmate.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author anjl
 */

@Slf4j
@RestController
@RequestMapping("/order")
@Api(tags = {"订单相关接口"}, description = "订单相关接口")
public class OrderRecordController extends BaseController {

    @Autowired
    private OrderRecordService orderRecordService;

    @AutoLog
    @PreAuthorize("isAuthenticated()")
    @GetMapping("/status")
    @ApiOperation(value = "APP调用-查询订单的本地状态-轮询使用 PAY_SUCCESS支付成功，PAY_WAITING未支付", response = ResultVO.class)
    public BusinessResult<OrderRecordDO> queryOrderFromLocal(@ApiParam(value = "商户订单号") @RequestParam String outTradeNo) {
        Object payWaitingOutTradeNo = redisTemplate.opsForValue().get(OrderRecordService.getWaitingPayOrderKey(outTradeNo));
        if (Objects.nonNull(payWaitingOutTradeNo)) {
            OrderRecordDO recordDO = OrderRecordDO.builder().orderStatus(OrderStatus.PAY_WAITING.name())
                    .outTradeNo(outTradeNo)
                    .build();
            return BusinessResult.createSuccessInstance(recordDO);
        }
        OrderRecordDO record = orderRecordService.findByOutTradeNo(outTradeNo);
        if (Objects.isNull(record)) {
            throw new CheckParamException("未查询到支付记录！outTradeNo = " + outTradeNo);
        }
        if (StringUtils.isBlank(record.getOrderStatus())) {
            throw new CheckParamException("支付状态为空！outTradeNo = " + outTradeNo);
        }
        //防止支付成功未发货，返回成功
        if(record.getOrderStatus().equals(OrderStatus.PAY_SUCCESS.name()) && YN.NO.code.equals(record.getSend())){
            record.setOrderStatus(OrderStatus.PAY_WAITING.name());
        }
        return BusinessResult.createSuccessInstance(record);
    }

}